//
//  LS_CustomTabBarController.m
//  breadPro
//
//  Created by 刘文超 on 2019/7/3.
//  Copyright © 2019 刘文超. All rights reserved.
//

#import "LS_CustomTabBarController.h"
#import "LS_CustomTabbar.h"
#import "LS_CustomTabBarButton.h"
#import <objc/runtime.h>

NSString *const LS_TabBarItemTitle = @"LS_TabBarItemTitle";
NSString *const LS_TabBarItemImage = @"LS_TabBarItemImage";
NSString *const LS_TabBarItemSelectImage = @"LS_TabBarItemSelectImage";

NSUInteger LS_CustomButtonIndex = 0;
NSUInteger LS_TabbarItemsCount = 0;
CGFloat LS_TabbarItemWidth = 0.0f;
NSString *const LS_TabBarItemWidthDidChangeNotification = @"LS_TabBarItemWidthDidChangeNotification";
static void * const LS_CenterButtonOffsetContext = (void *)&LS_CenterButtonOffsetContext;

@interface LS_CustomTabBarController()<UITabBarControllerDelegate>
@property(nonatomic,strong)UIImageView *launchImage;
@end
@implementation LS_CustomTabBarController
@synthesize viewControllers = _viewControllers;

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    //添加自定义的tabbar
    [self setUpTabBar];
    [self.tabBar addObserver:self forKeyPath:@"centerButtonOffset" options:NSKeyValueObservingOptionNew context:LS_CenterButtonOffsetContext];
    self.delegate = self;
    
    //1.设置启动图
    [self setLaunch];
    
}
-(void)setLaunch
{
    
    self.launchImage        = [[UIImageView alloc]initWithFrame:self.view.frame];
    self.launchImage.image  = [UIImage imageNamed:@"launch"];
    self.launchImage.tag    = 111;
    [self.view addSubview:self.launchImage];
    [self.view bringSubviewToFront:self.launchImage];
    @weakify(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        @strongify(self);
        [self endLaunch];
    });
    UIButton *btn           = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame               = CGRectMake(ScreenWidth - 80, 30, 60, 25);
    btn.backgroundColor     = LS_SetAColor(30, 30, 30, 0.7);
    btn.titleLabel.font     = LS_Font(14);
    btn.layer.cornerRadius  = 8;
    btn.layer.masksToBounds = YES;
    btn.tag                 = 222;
    [btn setTitle:@"跳过" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(endLaunch) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    
}
-(void)endLaunch
{
    if (![self.view viewWithTag:111])
    {
        return;
    }
    UIView *btn = [self.view viewWithTag:222];
    if (btn)
    {
        [btn removeFromSuperview];
    }
    @weakify(self);
    [UIView animateWithDuration:1.3 animations:^{
        @strongify(self);
        self.launchImage.transform  = CGAffineTransformMakeScale(1.3, 1.3);
        self.launchImage.alpha      = 0;
    } completion:^(BOOL finished) {
        [self.launchImage removeFromSuperview];
    }];
}
#pragma mark -
#pragma mark --选中底部动画效果
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    [self beginAnimation];
}
-(void)beginAnimation
{
    CATransition *animation         = [[CATransition alloc]init];
    animation.duration              = 0.5;
    animation.type                  = kCATransitionFade;
    animation.subtype               = kCATransitionFromRight;
    animation.timingFunction        = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    animation.accessibilityFrame    = CGRectMake(0,IS_IPhoneXSeries ? 88 : 64 , ScreenWidth, ScreenHeight);
    [self.view.layer addAnimation:animation forKey:@"switchView"];
}
#pragma mark -
#pragma mark - KVO Method
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if (context != LS_CenterButtonOffsetContext) {
        [super observeValueForKeyPath:keyPath ofObject:object change:change
                              context:context];
        return;
    }
    if (context == LS_CenterButtonOffsetContext) {
        CGFloat centerButtonOffset = [change[NSKeyValueChangeNewKey] floatValue];
        [self offsetTabBarSwappableImageViewToFit:centerButtonOffset];
    }
    
    
}
-(BOOL)shouldCustomizeImageInsets
{
    BOOL shouldCustomizeImageInsets = self.imageInsets.top != 0.f || self.imageInsets.left != 0.f || self.imageInsets.right != 0.f || self.imageInsets.bottom != 0;
    
    return shouldCustomizeImageInsets;
}
-(BOOL)shouldCustomizeTitlePositionAdjustment
{
    BOOL shouldCustomizeTitlePositionAdjustment = self.titlePositionAdjustment.horizontal != 0.f || self.titlePositionAdjustment.vertical != 0.f;
    return shouldCustomizeTitlePositionAdjustment;
}
-(void)offsetTabBarSwappableImageViewToFit:(CGFloat)centerButtonOffset
{
    if (self.shouldCustomizeImageInsets) {
        return ;
    }
    
    NSArray<UITabBarItem *> *tabBarItems = [self LS_tabBarController].tabBar.items;
    [tabBarItems enumerateObjectsUsingBlock:^(UITabBarItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIEdgeInsets imageInset = UIEdgeInsetsMake(centerButtonOffset, 0, -centerButtonOffset, 0);
        obj.imageInsets = imageInset;
        if (!self.shouldCustomizeTitlePositionAdjustment) {
            obj.titlePositionAdjustment = UIOffsetMake(0, MAXFLOAT);
        }
    }];
}
-(void)dealloc
{
    //移除KVO
    [self removeObserver:self forKeyPath:@"centerButtonOffset"];
}
-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    if (!self.tabBarHeight) {
        return;
    }
    self.tabBar.frame = ({
        CGRect rect = self.tabBar.frame;
        rect.size.height = self.tabBarHeight;
        rect.origin.y = self.view.frame.size.height - self.tabBarHeight;
        rect;
    });
}

/**
 利用KVO 把系统tabbar替换成自定义的
 */
-(void)setUpTabBar
{
    [self setValue:[LS_CustomTabbar new] forKey:@"tabBar"];
}
#pragma mark -
#pragma mark --delegete
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    NSInteger selectIndex = tabBarController.selectedIndex;
    UIButton *plusButton = LS_CustomButton;
    if (LS_CustomChildViewController) {
        if ((selectIndex == LS_CustomButtonIndex) && (viewController != LS_CustomChildViewController)) {
            plusButton.selected = NO;
        }
    }
    
    return YES;
}
-(void)setSelectedIndex:(NSUInteger)selectedIndex
{
    [super setSelectedIndex:selectedIndex];
    [self beginAnimation];
    [self setNoHighlighttabBar];
}
-(void)setSelectedViewController:(__kindof UIViewController *)selectedViewController
{
    [super setSelectedViewController:selectedViewController];
    [self setNoHighlighttabBar];
}
-(void)setNoHighlighttabBar
{
    NSArray *tabBarSubviews = [self.tabBar subviews];
    for (UIView *sub in tabBarSubviews) {
        for (UIView *insub in [sub subviews]) {
            if (insub && [NSStringFromClass([insub class]) isEqualToString:@"UITabBarSelectionIndicatorView"]) {
                [insub removeFromSuperview];
                break;
            }
        }
    }
}

-(instancetype)initWithViewControllers:(NSArray<UIViewController *> *)viewControllers tabBarItemsAttributes:(NSArray<NSDictionary *> *)tabBarItemsAttributes
{
    if (self = [super init]) {
        self.tabBarItemsAttribute = tabBarItemsAttributes;
        self.viewControllers = viewControllers;
    }
    return self;
}
+(instancetype)tabBarControllerWithViewControllers:(NSArray<UIViewController *> *)viewControllers tabBarItemsAttributes:(NSArray<NSDictionary *> *)tabBarItemsAttributes
{
    LS_CustomTabBarController *tabBar = [[LS_CustomTabBarController alloc]initWithViewControllers:viewControllers tabBarItemsAttributes:tabBarItemsAttributes];
    return tabBar;
    
}

+(BOOL)haveCustomButton
{
    if (LS_CustomButton) {
        return YES;
    }
    return NO;
}
-(UIWindow *)rootWindow
{
    UIWindow *result = nil;
    
    do {
        if ([[UIApplication sharedApplication].delegate respondsToSelector:@selector(window)]) {
            result = [[UIApplication sharedApplication].delegate window];
        }
        
        if (result) {
            break;
        }
    } while (NO);
    
    return result;
}

-(void)setViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers
{
    
    //清空所有的控制器
    if (_viewControllers && _viewControllers.count) {
        for (UIViewController *viewController in _viewControllers) {
            [viewController willMoveToParentViewController:nil];
            [viewController.view removeFromSuperview];
            [viewController removeFromParentViewController];
        }
    }
    
    //安全检测
    if (viewControllers && [viewControllers isKindOfClass:[NSArray class]]) {
        if ((!_tabBarItemsAttribute) || (_tabBarItemsAttribute.count != viewControllers.count)) {
            [NSException raise:@"LS_CustomTabBarController" format:@"设置_tabBarItemsAttributes属性时，确保元素个数与控制器的个数相同，并在方法`-setViewControllers:`之前设置"];
        }
        
        //判断是不是有中间按钮
        if (LS_CustomChildViewController) {
            NSMutableArray *viewControllerPlusButton = [[NSMutableArray alloc]initWithArray:viewControllers];
            [viewControllerPlusButton insertObject:LS_CustomChildViewController atIndex:LS_CustomButtonIndex];
            _viewControllers = [viewControllerPlusButton copy];
        }else{
            _viewControllers = [viewControllers copy];
        }
        
        LS_TabbarItemsCount = [viewControllers count];
        LS_TabbarItemWidth = ([UIScreen mainScreen].bounds.size.width - LS_CustomButtonWidth) /LS_TabbarItemsCount;
        NSInteger index = 0;
        for (UIViewController *viewController in _viewControllers) {
            NSString *title = nil;
            NSString *nomerImg = nil;
            NSString *selectImg = nil;
            if (viewController != LS_CustomChildViewController) {
                title = _tabBarItemsAttribute[index][LS_TabBarItemTitle];
                nomerImg = _tabBarItemsAttribute[index][LS_TabBarItemImage];
                selectImg = _tabBarItemsAttribute[index][LS_TabBarItemSelectImage];
            }else{
                index --;
             }
            
            [self addChildViewController:viewController WithTitle:title normalImageName:nomerImg selectedImageName:selectImg];
            [viewController LS_tabBarController];
            index ++ ;
        }
        
        
       
    }else{
        for (UIViewController *viewController in viewControllers) {
            [viewController LS_tabBarController];
        }
        _viewControllers = nil;
        
    }
}
-(void)addChildViewController:(UIViewController *)viewController WithTitle:(NSString *)title
              normalImageName:(NSString *)normalImageName
            selectedImageName:(NSString *)selectedImageName {
    
    viewController.tabBarItem.title = title;
    if (normalImageName) {
        UIImage *normalImage = [UIImage imageNamed:normalImageName];
        normalImage = [normalImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        viewController.tabBarItem.image = normalImage;
    }
    if (selectedImageName) {
        UIImage *selectedImage = [UIImage imageNamed:selectedImageName];
        selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        viewController.tabBarItem.selectedImage = selectedImage;
    }
    if (self.shouldCustomizeImageInsets) {
        viewController.tabBarItem.imageInsets = self.imageInsets;
    }
    if (self.shouldCustomizeTitlePositionAdjustment) {
        viewController.tabBarItem.titlePositionAdjustment = self.titlePositionAdjustment;
    }
    [self addChildViewController:viewController];
}
@end




@interface NSObject (LS_CustomTabBarControllerItmeInternal)
-(void)LS_setTabBarController:(LS_CustomTabBarController *)tabBarController;
@end
@implementation NSObject (LS_CustomTabBarControllerItmeInternal)

-(void)LS_setTabBarController:(LS_CustomTabBarController *)tabBarController
{
    objc_setAssociatedObject(self, @selector(LS_tabBarController), tabBarController, OBJC_ASSOCIATION_ASSIGN);
}

@end


@implementation NSObject (LS_CustomTabBarController)

-(LS_CustomTabBarController *)LS_tabBarController
{
    LS_CustomTabBarController *tabBarController = objc_getAssociatedObject(self, @selector(LS_tabBarController));
    if (!tabBarController) {
        if ([self isKindOfClass:[UIViewController class]] && [(UIViewController *)self parentViewController]) {
            tabBarController = [[(UIViewController *)self parentViewController] LS_tabBarController];
        }else{
            id<UIApplicationDelegate>delegate = ((id<UIApplicationDelegate>)[UIApplication sharedApplication].delegate);
            UIWindow *window = delegate.window;
            if ([window.rootViewController isKindOfClass:[LS_CustomTabBarController class]]) {
                tabBarController = (LS_CustomTabBarController *)window.rootViewController;
            }
        }
      
    } return tabBarController;
}

@end
